<template>
    <div>
        <div class="main-head flex-between container-fluid">
            <div class="title">
                <h1 v-text="$t('pro.UploadFile.UploadFile')"></h1>
            </div>
        </div>

        <div class="content container-fluid">
            <div class="breadcrumb">
                <a-breadcrumb :routes="routes">
                    <template slot="itemRender" slot-scope="{route, params, routes}">
            <span v-if="routes.indexOf(route) === routes.length - 1">
              {{route.breadcrumbName}}
            </span>
                        <router-link v-else :to="route.path">
                            {{route.breadcrumbName}}
                        </router-link>
                    </template>
                </a-breadcrumb>
            </div>
            <div class="portlet">
                <div class="tools">
                    {{$t('pro.UploadFile.Upload')}}
                    <span style="text-transform: capitalize;">{{fileType=='image'?$t('pro.UploadFile.Image'):$t('pro.UploadFile.Video')}}</span>
                </div>
                <a-spin :spinning="spinning" :tip="$t('pro.UploadFile.uploading')" >
                    <a-form class="upload-form" :form="form" @submit.prevent="handleSubmit">
                        <div class="upload-form-maxwidth">
                            <a-form-item>
                                <a-radio-group name="radioGroup" defaultValue="image" @change="fileTypeChange">
                                    <a-radio value="image">{{$t('pro.UploadFile.Image')}}</a-radio>
                                    <a-radio value="video">{{$t('pro.UploadFile.Video')}}</a-radio>
                                </a-radio-group>
                            </a-form-item>
                            <a-form-item :label="$t('pro.UploadFile.ReferenceURL')">
                                <a-input
                                        v-decorator="['fileManager.href',
                                                {
                                                    rules: [{ validator: checkHref },{ max: 150, message:  $t('pro.UploadFile.lengthMax')+'150' }],
                                                }
                                         ]"
                                />
                            </a-form-item>

                            <a-form-item :label="$t('pro.UploadFile.AlterText')" v-if="fileType == 'image'">
                                <a-input
                                        v-decorator="[
                                            'fileManager.alt',
                                            {rules: [{ max: 30, message:  $t('pro.UploadFile.lengthMax')+'30' }]}
                                        ]"
                                />
                            </a-form-item>
                        </div>

                        <uploader
                            :options="options"
                            :file-status-text="statusText"
                            class="uploader-example"
                            :autoStart="false"
                            ref="uploader"
                            @file-added="onFileAdded"
                            @fileAdded="onFileAdded"
                            @file-complete="fileComplete"
                            @complete="complete"
                        >
                            <uploader-unsupport></uploader-unsupport>
                            <uploader-drop>
                                <uploader-btn :attrs="attrsImage" v-show="isImage">{{$t('pro.UploadFile.SelectPictures')}}</uploader-btn>
                                <uploader-btn :attrs="attrsVideo" v-show="!isImage">{{$t('pro.UploadFile.ChooseVideo')}}</uploader-btn>
                            </uploader-drop>
                            <uploader-list></uploader-list>
                        </uploader>

                        <a-form-item>
                            <a-button type="primary" html-type="submit" icon="upload">{{$t('pro.UploadFile.StartUpload')}}</a-button>
                        </a-form-item>

                    </a-form>
                </a-spin>
            </div>
        </div>
    </div>
</template>
<script>
    import { addSonFile } from "@/api/file-manager";
    import { requestConfig } from '@/config'
    export default {
        data() {
            return {
                spinning: false, //加载
            
                fileManager: {
                    href: null,
                    alt: null,
                },
                fileLoad: {
                    height: '',
                    width: ''
                },
                fileType: "image",
                options: {
                    // 可通过 https://github.com/simple-uploader/Uploader/tree/develop/samples/Node.js 示例启动服务
                    target: requestConfig.baseURL + '/file-manager/chunk',
                    testChunks: true,
                    simultaneousUploads: 1,
                    chunkSize: 10 * 1024 * 1024,
                    headers: {
                        // 在header中添加的验证，请根据实际业务来
                        Authorization: window.sessionStorage.Authorization,
                        USER: JSON.parse(window.localStorage.userId)
                    },
                    categoryMap: {
                        image: ["gif", "jpg", "jpeg", "png", "bmp", "webp", "svg"],
                        video: [
                            "mp4",
                            "m3u8",
                            "rmvb",
                            "avi",
                            "swf",
                            "3gp",
                            "mkv",
                            "flv",
                            "ogg"
                        ],
                        audio: ["mp3", "wav", "wma", "aac", "flac"],
                        document: [
                            "doc",
                            "txt",
                            "docx",
                            "pages",
                            "epub",
                            "pdf",
                            "numbers",
                            "csv",
                            "xls",
                            "xlsx",
                            "keynote",
                            "ppt",
                            "pptx"
                        ]
                    }
                },
                attrsVideo: {
                    accept: "video/*"
                },
                attrsImage: {
                    accept: "image/*"
                },
                isImage: true,

                form: this.$form.createForm(this),
            };
        },
        computed: {
            parentDirectoryId() {
                return this.$route.params.id;
            },
            statusText() {
                return {
                    success: this.$t('pro.UploadFile.success'),
                    error: this.$t('pro.UploadFile.error'),
                    uploading: this.$t('pro.UploadFile.uploading'),
                    paused: this.$t('pro.UploadFile.paused'),
                    waiting: this.$t('pro.UploadFile.waiting'),
                }
            },
            routes() {
                return this.$t('pro.Library.routes')
            },
        },
        methods: {
            checkHref(rule, value, callback) {
                if (value) {
                    const pattern = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
                    if (pattern.test(value)) {
                        callback();
                    } else {
                        callback(
                            this.$t('pro.UploadFile.addressMess')
                        );
                    }
                } else {
                    callback("");
                }
            },

            handleSubmit(e) {
                e.preventDefault();
                this.spinning = true;
                this.form.validateFields((err, values) => {
                    let { length } = this.$refs.uploader.fileList
                    if (!err && length > 0) {
                        this.fileManager = values.fileManager;
                        const uploaderInstance = this.$refs.uploader.uploader;
                        uploaderInstance.resume();
                    }else {
                        this.spinning = false;
                        this.$message.warn('请上传完整信息')
                    }
                });
            },

             onFileAdded(file) {
                this.createReader(file.file,  (w, h) => {
                    this.fileLoad.width = w;
                    this.fileLoad.height = h;
                });

                if (this.fileType === "image") {
                    if (!file.fileType.includes("image")) {
                        file.cancel();
                    }
                }
                if (this.fileType === "video") {
                    if (file.fileType.includes("image")) {
                        file.cancel();
                    }
                }
            },

            /*
            * 接受一个文件类型。返回图片相干信息
            * 参数1： file
            * 参数2： 回调事件
            *
            * */
            createReader(file, whenReady) {
                let reader = new FileReader;
                reader.onload = (evt) => {
                    let image = new Image();
                    image.onload = function () {
                        let width = this.width;
                        let height = this.height;
                        if (whenReady) whenReady(width, height);
                    };
                    image.src = evt.target.result;
                };
                reader.readAsDataURL(file);
            },


            //视频图片 切换
            fileTypeChange(e) {
                this.fileType = e.target.value;
                this.isImage = this.fileType == "image";
            },

             // 一个根文件（文件夹）成功上传完成。
            fileComplete() {
                const file = arguments[0].file;
                let fileManager = this.fileManager;
                fileManager.fileName = file.name;
                fileManager.fileType = file.type;
                fileManager.fileSize = file.size;

                fileManager.remarks = arguments[0].uniqueIdentifier;
                fileManager.parentDirectoryId = +this.parentDirectoryId;
                fileManager.width = this.fileLoad.width;
                fileManager.height = this.fileLoad.height;
                addSonFile(fileManager);
                
            },
            
            // 上传完成
            complete() {
                this.spinning = false;
                this.$message.success(this.$t('pro.UploadFile.UploadCompleted'))
                setTimeout(() => {
                    this.$router.push({path: '/bidder/creativelibrary'})
                },300)
            },
        
        }
    };
</script>

<style lang="less">
    .ant-upload-select-picture-card i {
        font-size: 32px;
        color: #999;
    }

    .ant-upload-select-picture-card .ant-upload-text {
        margin-top: 8px;
        color: #666;
    }
    .uploader-example .uploader-file-info .uploader-file-actions span.uploader-file-resume{
        display: none;
    }
    .uploader-example .uploader-file-info .uploader-file-actions span.uploader-file-pause{
        display: none;
    }



    .uploader-example {
        width: 600px;
        padding: 15px;
        margin: 20px 0 20px 0;
        font-size: 12px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
    }

    @media (max-width: 767.98px){
        .uploader-example {
            width: 95%;
        }
    }
    @media (max-width: 555.98px){
        .uploader-example {
            width: 100%;
        }
    }


    .uploader-example .uploader-btn {
        margin-right: 4px;
    }
    .uploader-example .uploader-list {
        max-height: 440px;
        overflow: auto;
        overflow-x: hidden;
        overflow-y: auto;
    }

    .upload-form {
        > span {
            display: block;
            overflow: hidden;
        }
    }
    .upload-form-maxwidth {
        max-width: 500px;
    }
</style>

